package com.zjlanyun.erp.customer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.aihook.pulltorefresh.lib.XListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.zjlanyun.erp.Common;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.utils.Toastor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;

import cz.msebera.android.httpclient.Header;

/**
 * @author:shun
 * @date:2016年2月17日 下午4:50:57
 * @version:V_1.0
 * @Description:
 */

public class Customer extends Activity implements XListView.IXListViewListener {

    private XListView list;
    private TextView title;
    private LinearLayout ll_back;
    private ArrayList<HashMap<String, Object>> mList;
    private SimpleAdapter mSimpleAdapter;
    private Handler mHandler;
    private Context mContext = this;
    private int page = 0;
    private EditText et_keyword;
    private ImageView clearKeyword; // 清除搜索内容按钮
    private Button btn_search; // 搜索按钮
    private String keyword = ""; // 关键词
    private Toastor toastor;
    private HashMap<String, Object> userinfo; // 用户资料，配置
    private String serverUrl = ""; // 服务器地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customer);
        initView();
        getData();
    }

    // 初始化View
    @SuppressLint({"NewApi", "InlinedApi"})
    private void initView() {
        title = (TextView) findViewById(R.id.title);
        list = (XListView) findViewById(R.id.list);
        ll_back = (LinearLayout) findViewById(R.id.ll_back);
        btn_search = (Button) findViewById(R.id.btn_search);
        et_keyword = (EditText) findViewById(R.id.et_keyword);
        clearKeyword = (ImageView) findViewById(R.id.clearKeyword);

        title.setText("客户管理(50)");
        toastor = new Toastor();
        userinfo = Common.getUserinfo(mContext);
        serverUrl = WebApi.customer(mContext);

        list.setPullLoadEnable(true);
        list.setOverScrollMode(View.OVER_SCROLL_NEVER);
        list.setRefreshTime("刚刚");
        mHandler = new Handler();
        list.setXListViewListener(this);
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, CustomerDetail.class);
                intent.putExtra("FItemID", Integer.parseInt(mList.get(position - 1).get("FItemID").toString()));
                startActivity(intent);
            }
        });

        // 监听listview滚动
        list.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 隐藏软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                et_keyword.clearFocus();
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });

        // 监听关键词输入
        et_keyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!s.equals("")) {
                    clearKeyword.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        // 搜索
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyword = et_keyword.getText().toString();
                if (keyword.equals("")) {
                    toastor.showShortToast("请输入关键词");
                } else {
                    page = 0;
                    list.setPullLoadEnable(true);
                    getData();

                    // 隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    et_keyword.clearFocus();
                }
            }
        });

        // 清除搜索关键词
        clearKeyword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_keyword.setText("");
                keyword = "";
                page = 0;
                list.setPullLoadEnable(true);
                getData();
                // 隐藏清除按钮
                clearKeyword.setVisibility(View.GONE);

                // 隐藏软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                et_keyword.clearFocus();
            }
        });

        // 后退
        ll_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    // 获取数据
    private void getData() {
        page++;
        if (page == 1) {
            mList = new ArrayList<HashMap<String, Object>>();
            mSimpleAdapter = new SimpleAdapter(mContext, mList, R.layout.customer_item,
                    new String[]{"FName", "FContact", "FPhone"},
                    new int[]{R.id.fname, R.id.fcontact, R.id.fphone});
            list.setAdapter(mSimpleAdapter);
        }
        if ((Boolean) userinfo.get("isDemo")) {
            // 测试的
            if (page > 4)
                list.setPullLoadEnable(false);
            int[] FItemID = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            String[] FName = {"广州郭", "广州廖", "长荣", "广州叶", "广州刘", "广州邵", "广州何", "广州曹", "广州曾", "广州胡"};
            String[] FContact = {"郭经理", "廖经理", "长经理", "叶经理", "刘经理", "邵经理", "何经理", "曹经理", "曾经理", "胡经理"};
            String[] FPhone = {"13968687878", "13968687878", "13968687878", "13968687878", "13968687878",
                    "13968687878", "13968687878", "13968687878", "13968687878", "13968687878"};
            for (int i = 0; i < FName.length; i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("FItemID", FItemID[i]);
                map.put("FName", FName[i]);
                map.put("FContact", FContact[i]);
                map.put("FPhone", FPhone[i]);
                mList.add(map);
            }
            mSimpleAdapter.notifyDataSetChanged();
        } else {
            AsyncHttpClient client = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("page", page);
            params.put("keyword", keyword);
            params.put("type", "list");
            params.put("username", userinfo.get("username"));
            params.put("password", userinfo.get("password"));
            client.post(serverUrl, params, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    toastor.showShortToast(Data.SERVER_URL_ERROR);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    JSONTokener jsonParser = new JSONTokener(responseString);
                    try {
                        JSONObject json = (JSONObject) jsonParser.nextValue();
                        if (json.getInt("code") == 0) {
                            JSONObject data = json.getJSONObject("data");
                            JSONArray jsonArray = data.getJSONArray("Table1");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject item = jsonArray.getJSONObject(i);
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("FItemID", item.getInt("FItemID"));
                                map.put("FName", item.getString("FName"));
                                map.put("FContact", item.getString("FContact"));
                                map.put("FPhone", item.getString("FPhone"));
                                mList.add(map);
                            }
                            JSONArray table = data.getJSONArray("Table");
                            JSONObject tableItem = table.getJSONObject(0);
                            if (page >= tableItem.getInt("PageCount")) {
                                list.setPullLoadEnable(false);
                            }
                            if (page == 1) {
                                title.setText("客户管理(" + tableItem.getInt("Total") + ")");
                            }
                            mSimpleAdapter.notifyDataSetChanged();
                        } else {
                            toastor.showShortToast(json.getString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        stopLoad();
    }

    // 刷新停止
    private void stopLoad() {
        list.stopRefresh();
        list.stopLoadMore();
        list.setRefreshTime("");
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 0;
                list.setPullLoadEnable(true);
                getData();
            }
        }, 1200);
    }

    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            public void run() {
                getData();
            }
        }, 500);
    }

}
